<!-- 需求单 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft" slot-scope="{ size }">
        <el-button type="primary" :size="size" @click="exportExcel()"
          >导出</el-button
        >
      </template>
      <template slot-scope="{ row }" slot="menu">
        <el-button
          type="text"
          size="mini"
          icon="el-icon-view"
          @click.stop="view(row)"
          >详情</el-button
        >
        <el-button
          type="text"
          size="mini"
          icon="el-icon-close"
          v-if="
            row.demandStatus !== 'abolished' &&
            permission.tms_demandorder_toVoid
          "
          @click.stop="toVoid(row)"
          >作废</el-button
        >
        <el-button
          type="text"
          size="mini"
          icon="el-icon-view"
          v-if="
            row.demandStatus === 'abolished' &&
            permission.tms_demandorder_viewToVoid
          "
          @click.stop="viewToVoid(row)"
          >作废原因</el-button
        >
        <span
          v-if="specialTransport.indexOf(row.orderType) === -1"
          style="margin-left: 10px"
        >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="row.demandStatus === 'already'"
            @click.stop="distribution(row)"
            >分配运单</el-button
          >
        </span>
        <span
          v-if="specialTransport.indexOf(row.orderType) === -1"
          style="margin-left: 10px"
        >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-share"
            v-if="
              row.demandStatus === 'already' &&
              permission.tms_demandorder_viewToVoid
            "
            @click.stop="transfer(row)"
            >转交</el-button
          >
        </span>
        <span style="margin-left: 10px" v-else>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="
              row.demandStatus !== 'wait' &&
              row.demandStatus !== 'rejected' &&
              row.demandStatus !== 'finish'
            "
            @click.stop="completion(row)"
            >补全信息</el-button
          >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="row.demandStatus === 'already'"
            @click.stop="edit(row.id, 'toBeLoaded', '到达提货点')"
            >到达提货点</el-button
          >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="row.demandStatus === 'toBeLoaded'"
            @click.stop="edit(row.id, 'toBeShipped', '已装货')"
            >已装货</el-button
          >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="row.demandStatus === 'toBeShipped'"
            @click.stop="edit(row.id, 'awaitingDelivery', '已启运')"
            >已启运</el-button
          >
          <el-button
            type="text"
            size="mini"
            icon="el-icon-edit"
            v-if="row.demandStatus === 'awaitingDelivery'"
            @click.stop="edit(row.id, 'finish', '已运达')"
            >已运达</el-button
          >
        </span>
      </template>
    </avue-crud>
    <demandDetail ref="demandDetail" />
    <carrierList ref="carrierList" @refresh="refresh" />
    <assignWaybill ref="assignWaybill" @refresh="refresh" />
    <completionInfo ref="completionInfo" @refresh="refresh" />
    <tipsDialog ref="tipsDialog" />
  </basic-container>
</template>

<script>
import {
  getList,
  demandExtraEvent,
  demandorderToVoid,
} from "@/api/transportation/demandorder";
import demandDetail from "./components/demandDetail";
import assignWaybill from "./components/assignWaybill";
import completionInfo from "./components/completionInfo";
import tipsDialog from "./components/tipsDialog";
import carrierList from "./components/carrierList";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import { serialize } from "@/util/util";
import { getBeforeCurrentDateDays } from "@/util/date";

export default {
  data() {
    return {
      form: {},
      query: {},
      specialTransport: ["ZFO3", "ZFO9", "ZFB1", "ZFB2"],
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: "auto",
        calcHeight: 30,
        tip: false,
        index: true,
        searchShow: true,
        searchLabelWidth: 100,
        searchSpan: 6,
        searchMenuSpan: 4,
        border: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        labelWidth: "180",
        menuWidth: "200",
        column: [
          {
            label: "需求单号",
            prop: "demandOrderNumber",
            // search: true,
            width: 120,
            editDisplay: false,
            addDisplay: false,
          },

          {
            label: "需求单状态",
            prop: "demandStatus",
            type: "select",
            width: 100,
            searchLabelWidth: "100",
            props: {
              label: "value",
              value: "key",
            },
            // search: true,
            dicUrl: `/api/blade-tms/common/SelectEnum?name=demandStatus`,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "货运订单",
            prop: "orderNo",
            // search: true,
            width: 100,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "货运订单类型",
            prop: "orderType",
            type: "select",
            multiple: true,
            width: 100,
            searchLabelWidth: "100",
            props: {
              label: "value",
              value: "key",
            },
            search: true,
            dicUrl: `/api/blade-tms/common/SelectEnum?name=torType`,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "交货单",
            prop: "deliverNo",
            search: true,
            width: 100,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "订单号",
            prop: "orderNumber",
            width: 100,
          },
          {
            label: "承运商",
            prop: "carrierName",
            search: true,
            width: 120,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "分包商",
            prop: "fbsName",
            width: 120,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "提单号",
            width: 100,
            prop: "billOfLadingNumber",
          },
          {
            label: "客户名称",
            width: 100,
            prop: "customerName",
          },
          {
            label: "国际贸易条款",
            width: 100,
            prop: "tradeTerms",
          },
          {
            label: "条款附加信息",
            width: 100,
            prop: "tradeTermsItem",
          },
          {
            label: "源位置",
            prop: "startLocationName",
            width: 100,
            // search: true,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "目标位置",
            width: 100,
            prop: "targetLocationName",
            // search: true,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "源位置街道",
            width: 150,
            prop: "sourceLocationStreet",
          },
          {
            label: "目标位置街道",
            width: 150,
            prop: "destinationStreet",
          },
          {
            label: "物料信息",
            width: 100,
            prop: "materialInformation",
          },
          {
            label: "合同公司",
            width: 100,
            prop: "contractCompany",
          },
          {
            label: "计划提货日期",
            width: 100,
            prop: "planGetGoodsDateStart",
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "计划收货日期",
            width: 95,
            prop: "planGetGoodsDateEnd",
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "计划提货日期",
            type: "date",
            prop: "planGetGoodsDate",
            search: true,
            searchLabelWidth: "100",
            searchRange: true,
            editDisplay: false,
            addDisplay: false,
            hide: true,
            showColumn: false,
            searchValue: this.getInitDate(),
            // defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            startPlaceholder: "请选择开始日期",
            endPlaceholder: "请选择结束日期",
          },
          {
            label: "计划收货日期",
            type: "datetime",
            prop: "plannedDeliveryDate",
            search: true,
            searchLabelWidth: "100",
            searchRange: true,
            hide: true,
            editDisplay: false,
            addDisplay: false,
            // hide: true,
            showColumn: false,
            defaultValue: ["2024-04-04", "2024-04-04"],
            defaultTime: ["00:00:00", "23:59:59"],
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            startPlaceholder: "请选择开始日期",
            endPlaceholder: "请选择结束日期",
          },
        ],
      },
      data: [],
    };
  },
  components: {
    demandDetail,
    assignWaybill,
    completionInfo,
    tipsDialog,
    carrierList,
  },
  computed: {
    ...mapGetters(["permission"]),
  },
  methods: {
    getInitDate() {
      let startDate = [
        getBeforeCurrentDateDays(-1),
        getBeforeCurrentDateDays(2),
      ];
      return startDate;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (!params.planGetGoodsDate) {
        this.$message("请选择计划提货日期");
        done();
        return;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    refresh() {
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      let query = Object.assign(params, this.query);
      let initDate = this.getInitDate();
      if (query.planGetGoodsDate) {
        query = {
          ...query,
          planGetGoodsDateStart: query.planGetGoodsDate
            ? query.planGetGoodsDate[0] + " 00:00:00"
            : "",
          planGetGoodsDateEnd: query.planGetGoodsDate
            ? query.planGetGoodsDate[1] + " 00:00:00"
            : "",
        };
        delete query.planGetGoodsDate;
      } else {
        query = {
          ...query,
          planGetGoodsDateStart: initDate[0] + " 00:00:00",
          planGetGoodsDateEnd: initDate[1] + " 00:00:00",
        };
      }
      if (query.plannedDeliveryDate) {
        query = {
          ...query,
          plannedDeliveryDateStart: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[0]
            : "",
          plannedDeliveryDateEnd: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[1]
            : "",
        };
        delete query.plannedDeliveryDate;
      }
      if (query.orderType && typeof query.orderType === "object") {
        query = {
          ...query,
          freightOrderTypes: query.orderType.join(","),
        };
        delete query.orderType;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, query).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.$nextTick(() => {
          this.$refs.crud.$refs.table.doLayout();
        });
      });
    },
    //详情
    view(row) {
      this.$refs.demandDetail.open(row.id, row.orderType);
    },
    //分配运单
    distribution(row) {
      this.$refs.assignWaybill.open(
        row.id,
        row.carrierNo,
        row.orderType,
        "add",
        "",
        ""
      );
    },
    //转交
    transfer(row) {
      this.$refs.carrierList.open(row.id);
    },
    //补全信息
    completion(row) {
      this.$refs.completionInfo.open(row.id, row.orderType);
    },
    //作废
    toVoid(row) {
      this.$prompt("请输入作废原因", "作废原因", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /\S/,
        inputErrorMessage: "请输入作废原因",
      })
        .then(({ value }) => {
          demandorderToVoid({ id: row.id, reasonForVoiding: value }).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {});
    },
    //查看作废原因
    viewToVoid(row) {
      this.$refs.tipsDialog.open("作废原因", row.reasonForVoiding);
    },
    //修改状态
    edit(demandId, status, title) {
      this.$confirm(`是否确定${title}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          demandExtraEvent({ demandId: demandId, status: status }).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
            },
            (error) => {
              window.console.log(error);
            }
          );
        })
        .catch(() => {});
    },
    //导出
    exportExcel() {
      let query = this.$refs.crud.$refs.headerSearch.searchForm;
      if (query.planGetGoodsDate && query.planGetGoodsDate.length > 0) {
        query = {
          ...query,
          planGetGoodsDateStart: query.planGetGoodsDate
            ? query.planGetGoodsDate[0]
            : "",
          planGetGoodsDateEnd: query.planGetGoodsDate
            ? query.planGetGoodsDate[1]
            : "",
        };
      }
      if (query.plannedDeliveryDate && query.plannedDeliveryDate.length > 0) {
        query = {
          ...query,
          plannedDeliveryDateStart: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[0]
            : "",
          plannedDeliveryDateEnd: query.plannedDeliveryDate
            ? query.plannedDeliveryDate[1]
            : "",
        };
      }
      if (query.orderType && typeof query.orderType === "object") {
        query = {
          ...query,
          freightOrderTypes: query.orderType.join(","),
        };
      }
      delete query.orderType;
      delete query.plannedDeliveryDate;
      delete query.planGetGoodsDate;
      var url = `/api/blade-tms/demandorder/DemandList/download?Blade-Auth=bearer ${getToken()}&${serialize(
        query
      )}`;
      this.downFile(url);
    },
  },
};
</script>

<style></style>
